package handler

import (
	"encoding/json"
	"github.com/golang-jwt/jwt/v5"
	"github.com/xiyoufang/cloud-syncer/internal/env"
	"github.com/xiyoufang/cloud-syncer/internal/http/model"
	"github.com/xiyoufang/cloud-syncer/internal/util"
	"net/http"
	"time"
)

func LoginHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	var req model.LoginReq
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		env.Logger().Error(err.Error())
		http.Error(w, "Invalid request payload", http.StatusBadRequest)
		return
	}
	httpCfg := env.Config().Http
	password := util.Sha512Hex([]byte(req.Password), []byte(httpCfg.SecretKey))
	if !(req.Username == httpCfg.Username && password == httpCfg.Password) { // 密码错误
		env.Logger().Debug("username: %v, password: %v", req.Username, password)
		response := model.ResponseBodyEntity{
			Code:    model.MethodArgumentNotValid,
			Message: "账号或者密码错误",
		}
		if err := json.NewEncoder(w).Encode(response); err != nil {
			env.Logger().Error(err.Error())
			http.Error(w, "Failed to encode response", http.StatusInternalServerError)
			return
		}
	} else {
		claims := &jwt.RegisteredClaims{}
		tokenString, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(httpCfg.SecretKey))
		if err != nil {
			env.Logger().Error("生成 Token 出错: %v", err)
			return
		}
		env.Cache().SetWithTtl(tokenString, make(map[string]interface{}), time.Duration(env.Config().Http.SessionTimeout)*time.Second)
		response := model.ResponseBodyEntity{
			Code:    model.OK,
			Message: "success",
			Data:    &model.LoginVO{Token: tokenString},
		}
		if err := json.NewEncoder(w).Encode(response); err != nil {
			env.Logger().Error(err.Error())
			http.Error(w, "Failed to encode response", http.StatusInternalServerError)
			return
		}
	}
}
